<?php

ob_start('ob_gzhandler');
header("Content-type: text/html; charset=UTF-8");

$inc = dirname(__FILE__);
require $inc.'/config.inc.php';
require_once $inc.'/adodb_lite/adodb.inc.php';
require_once $inc.'/adodb_lite/adodb-errorhandler.inc.php';


function __autoload($name) {
	global $inc;
	if(eregi('pear',$name)) return false;
	
	if ($name == 'Smarty') {
		include_once $inc.'/smarty/Smarty.class.php';
	
	} elseif(ereg("plugin_",$name)) { 
		include_once $inc.'/plugins/'.substr($name,7).'/plugin.php';
		
	} elseif(ereg("ADO",$name)) {
		$driver = substr($name,0,strpos($name,'_'));
		include_once $inc.'/adodb_lite/adodbSQL_drivers/'.$driver.'/'.$driver.'_driver.inc';
	
	} else {
		include_once $inc.'/classes/class.'.$name.'.php';
	}
	
	if (!class_exists($name, false)) {
		eval('class ' . $name . ' { ' .
		'    public function __construct() { ' .
		'        throw new Exception("Class ' . $name . ' not found."); ' .
		'    } ' .
		'}');
	}
}

session_start();
if(isset($_GET['reset'])) session_destroy();

// Get database up and runnin'
if(!isset($_SESSION['db'])) {
	$_SESSION['db'] =& ADONewConnection($db_config['databasetype']);
}
$_SESSION['db']->PConnect($db_config['hostname'], $db_config['username'], $db_config['password'], $db_config['databasename']) or die("database connection failed");
$_SESSION['db']->execute("SET NAMES `utf8` COLLATE `utf8_general_ci`");

if(!isset($_SESSION['joel'])) { $_SESSION['joel'] = new Joel(); }
if(!isset($_SESSION['clipboard'])) { $_SESSION['clipboard'] = new Clipboard(); }


/**
* JSON-Ajax decoder
*
* Expects a Json String as POST Parameter
*/
if(isset($_POST['json'])) {
	$json = new Services_JSON();
	$myobj = $json->decode(preg_replace('/[\n\r]+/', '\n', $_POST['json'])) 
		or die("error: DATA could not be parsed from json");
	
	$myclassname = isset($myobj->classname) ? $myobj->classname : 'joel';
	$myfunction = $myobj->method;
	
	if($myclassname != 'joel') {
		if(isset($_SESSION['joel']->plugins['plugin_'.$myclassname])) {
			$class = $_SESSION['joel']->plugins['plugin_'.$myclassname];
		} else {
			die("error: Provided class ".$myclassname." does not exist or is not accessible");
		}
	} else {
		$class = $_SESSION['joel'];
	}
	
	if(method_exists($class,$myfunction)) {
		$param = isset($myobj->parameter) ? $myobj->parameter : false;
		$class->$myfunction($param);
		
	} else {
		die('error: Method "'.$myfunction.'" does not exists in class "'.$myclassname.'"');
	}
}

?>